package com.sk.weichat.ui.circle;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.adapter.SearchLocationListAdapter;
import com.sk.weichat.bean.DynamicLoactionBean;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.base.EditBaseActivity;
import com.sk.weichat.util.AppUtils;
import com.sk.weichat.util.ToastUtil;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import okhttp3.Call;

/**
 * @Author: chenzl
 * @ClassName: SearchLocationListActivity
 * @Description: 位置地点搜索
 * @CreateDate: 2019/10/23 18:20
 */
public class SearchLocationListActivity extends EditBaseActivity {

    private LinearLayout ll_layout_search_empty;
    private EditText et_search_user;
    private ImageView iv_clear_user;
    private TextView tv_finish_search_user;

    private SmartRefreshLayout refreshLayout;
    private RecyclerView recy_location;

    private List<DynamicLoactionBean.LoactionResult> mLoactionResult = new ArrayList<>();
    private SearchLocationListAdapter mSearchLocationListAdapter;
    //    private PoiSearch mPoiSearch;
    private Double currentLatitude;
    private Double currentLongitude;
    private int mPage = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_location_list);
        getSupportActionBar().hide();
        initView();
    }

    private void initView() {

        ll_layout_search_empty = findViewById(R.id.ll_layout_search_empty);
        et_search_user = findViewById(R.id.et_search_user);
        iv_clear_user = findViewById(R.id.iv_clear_user);
        iv_clear_user.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_search_user.setText("");
            }
        });
        tv_finish_search_user = findViewById(R.id.tv_finish_search_user);
        tv_finish_search_user.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        recy_location = findViewById(R.id.recy_location);
        recy_location.setLayoutManager(new LinearLayoutManager(this));
        mSearchLocationListAdapter = new SearchLocationListAdapter(mLoactionResult);
        mSearchLocationListAdapter.setHasStableIds(true);
        recy_location.setAdapter(mSearchLocationListAdapter);
        mSearchLocationListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                DynamicLoactionBean.LoactionResult mLoaction = mLoactionResult.get(position);
                Intent intent = new Intent(SearchLocationListActivity.this, DynamicLocationListActivity.class);
                intent.putExtra("LoactionResult", mLoaction);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recy_location.getItemAnimator()).setSupportsChangeAnimations(false);

        refreshLayout = findViewById(R.id.refresh_search_location);
        refreshLayout.setDragRate(0.4f);//刷新拉动阻尼效果，数值越小，拉动距离越大
        refreshLayout.setEnableOverScrollBounce(false);//禁止越界回弹
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.setNoMoreData(false);
                mPage = 0;
                LoadLoaction(currentLatitude, currentLongitude, et_search_user.getText().toString(), mPage,false);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPage++;
                LoadLoaction(currentLatitude, currentLongitude, et_search_user.getText().toString(), mPage,false);
            }
        });


        currentLatitude = MyApplication.getInstance().getBdLocationHelper().getLatitude();
        currentLongitude = MyApplication.getInstance().getBdLocationHelper().getLongitude();
//        mPoiSearch = PoiSearch.newInstance();
//        mPoiSearch.setOnGetPoiSearchResultListener(this);

//        AppUtils.showSoftKeyboard(mContext,et_search_user);
        et_search_user.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) {
                    iv_clear_user.setVisibility(View.INVISIBLE);
                    ll_layout_search_empty.setVisibility(View.GONE);
                    mLoactionResult.clear();
                    mPage = 0;
                    mSearchLocationListAdapter.notifyDataSetChanged();
                    return;
                }
                iv_clear_user.setVisibility(View.VISIBLE);
                mPage = 0;
                LoadLoaction(currentLatitude, currentLongitude, et_search_user.getText().toString(), mPage,true);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }


    /**
     * @author: czl
     * @description 加载当前 附近位置
     * @date: 2019/10/23 17:05
     */
    private void LoadLoaction(double latitude, double longitude, String query, int pageNum,boolean isShow) {
//        if (isShow){
//            DialogHelper.showDefaulteMessageProgressDialog(this);
//        }
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("latitude", String.valueOf(latitude));
        params.put("longitude", String.valueOf(longitude));
        params.put("radius", "2000");
        params.put("query", query);
        params.put("pageIndex", String.valueOf(pageNum));
        params.put("pageSize", String.valueOf(20));

        HttpUtils.post().url(coreManager.getConfig().MAP_PLACE_SEARCH)
                .params(params)
                .build()
                .execute(new BaseCallback<DynamicLoactionBean>(DynamicLoactionBean.class) {
                    @Override
                    public void onResponse(ObjectResult<DynamicLoactionBean> result) {
//                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            refreshLayout.setVisibility(View.VISIBLE);
                            List<DynamicLoactionBean.LoactionResult> datas = result.getData().getResults();

                            if (mPage == 0) {
                                refreshLayout.finishRefresh();
                                mLoactionResult.clear();
                            } else if (datas.size() == 10) {
                                refreshLayout.finishLoadMoreWithNoMoreData();
                            } else {
                                refreshLayout.finishLoadMore();
                            }
                            mLoactionResult.addAll(datas);
                            mSearchLocationListAdapter.setKeyword(et_search_user.getText().toString());
                            mSearchLocationListAdapter.notifyDataSetChanged();
                            if (datas.size() == 0&& mPage==0) {
                                ll_layout_search_empty.setVisibility(View.VISIBLE);
                            } else {
                                ll_layout_search_empty.setVisibility(View.GONE);
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showToast(SearchLocationListActivity.this, e.getMessage());
                    }
                });
    }
}
